package model

import (
	"time"
)

type (
	LogItem struct {
		ID        uint      `json:"id"`
		CreatedAt time.Time `json:"created_at"`
		RequestID string    `json:"request_id"`
		IP        string    `json:"ip"`
		Method    string    `json:"method"`
		Path      string    `json:"path"`
		Status    int       `json:"status"`
		Latency   int64     `json:"latency"`
		Agent     string    `json:"agent"`
		Response  string    `json:"response" gorm:"column:response;type:text"`
		Username  string    `json:"username"`
		NickName  string    `json:"nickname"`
		RoleID    int       `json:"role_id"`
		UserID    int       `json:"user_id"`
	}
)

func (l LogItem) TableName() string {
	return "operation_log"
}

func GetLogs(index, size int) ([]*LogItem, int, error) {
	logs := make([]*LogItem, 0)
	total := 0

	if err := db.Model(&LogItem{}).Count(&total).Error; err != nil {
		return nil, -1, err
	}

	if err := db.Model(&LogItem{}).Order("created_at desc").Offset((index - 1) * size).Limit(size).Find(&logs).Error; err != nil {
		return nil, -1, err
	}

	return logs, total, nil
}

func DeleteLogByIDs(ids []int) error {
	if err := db.Where("id in (?)", ids).Delete(&LogItem{}).Error; err != nil {
		return err
	}
	return nil
}
